<template>
  <el-card>
    <el-row style="margin:10px 0;">
      <el-col :span="8">
        <el-button style="display: flex;" type="primary" @click="bindRoleModules">绑定</el-button>
      </el-col>
    </el-row>

    <el-row justify="start">
      <el-col :span="4" style="display:flex;justify-content:start;">
        <el-card>
          <div slot="header">
            <span>绑定角色</span>
          </div>
          <el-select placeholder="请选择角色" v-model="currentRoleId" @change="changeRole">
            <el-option
              v-for="item in roles"
              :key="item.roleId"
              :label="item.roleName"
              :value="item.roleId">
            </el-option>
          </el-select>
        </el-card>
      </el-col>
      <el-col :span="4">
        <el-card>
          <div slot="header" style="display:flex;justify-content:start;">
            <span>对应菜单</span>
          </div>
          <el-tree
            ref="treeRef"
            :data="moduleTree"
            show-checkbox
            node-key="id"
            :default-expanded-keys="expandKeys"
            :default-checked-keys="defaultCheckedKeys"
            :props="defaultProps">
          </el-tree>
        </el-card>
      </el-col>
    </el-row>

  </el-card>
</template>

<script>
    import api from '../../../utils/api';

    export default {
        name: "RoleManage",
        data() {
            return {
                currentRoleId: null,
                roles: [],
                expandKeys: [],
                moduleTree: [],
                defaultCheckedKeys: [],
                defaultProps: {
                    children: 'children',
                    label: 'label'
                },
            }
        },
        methods: {
            getModules() {
                var that = this;
                api.ajax.get("/module/get").then(function (result) {
                    var modules = result.data;
                    var expandKeys = [];
                    for (let i = 0; i < modules.length; i++) {
                        expandKeys.push(modules[i].id);
                    }
                    that.expandKeys = expandKeys;
                    that.moduleTree = modules;
                    that.getRoles();
                    //加载默认角色的选中菜单
                }, function (result) {
                    // console.log(result);
                    that.$alert("获取模块信息异常", '失败!');
                });
            },
            getRoles() {
                var that = this;
                api.ajax.get("/role/get/all").then(function (result) {
                    var roles = result.data;
                    that.roles = roles;
                    //默认加载第一个角色的模块
                    if (roles.length > 0) {
                        that.currentRoleId = roles[0].roleId;
                        that.getUserRoles(roles[0].roleId);
                    }
                }, function (result) {
                    // console.log(result);
                    that.$alert("获取角色信息失败", '失败!');
                });
            },
            getUserRoles(roleId) {
                var that = this;
                api.ajax.get("/role/get?roleId=" + roleId).then(function (result) {
                    var modules = result.data;
                    that.matchModules(modules);
                }, function (result) {
                    // console.log(result);
                    that.$alert("获取该角色的模块信息失败", '失败!');
                });
            },
            matchModules(modules) {
                // console.log(modules);
                var selectedModules = [];
                for (let i = 0; i < modules.length; i++) {
                    selectedModules.push(modules[i].id);
                }
                // console.log(selectedModules);
                // console.log(this.moduleTree);
                var keys = [];
                //匹配选中子菜单，
                for (let i = 0; i < this.moduleTree.length; i++) {
                    // console.log(this.moduleTree[i].children)
                    // if (selectedModules.includes(this.moduleTree[i].id)) {
                    //     keys.push(this.moduleTree[i].id);
                    // }
                    for (let j = 0; j < this.moduleTree[i].children.length; j++) {
                        if (selectedModules.includes(this.moduleTree[i].children[j].id)) {
                            keys.push(this.moduleTree[i].children[j].id);
                        }
                    }
                }
                // console.log(keys);
                this.defaultCheckedKeys = keys;
            },
            changeRole(roleId) {
                this.$refs.treeRef.setCheckedKeys([]);
                this.defaultCheckedKeys = [];
                this.getUserRoles(roleId);
            },
            //一个角色绑定多个菜单的绑定
            bindRoleModules() {
                var that = this;
                var checkedRoles = [];
                for (let role of this.$refs.treeRef.getCheckedNodes()) {
                    // console.log(role);
                    checkedRoles.push(role.module_id);
                }

                //针对根节点下子节点非全部勾选处理
                //1.主节点不存在的遍历，若有子节点，则需要存储
                for(let tree of this.moduleTree){
                    //2.记录主节点不存在的标志
                    let parentBool = false;
                    for(let c of checkedRoles) {
                        if(c == tree.module_id){
                            parentBool = true;
                            break;
                        }
                    }
                    //3.处理
                    if(!parentBool){
                        checkedRoles.push(tree.module_id);
                    }
                }
                //4.重新排序[从小往大]
                checkedRoles.sort((a, b) => a - b);

                var params = {
                    role_id: this.currentRoleId,
                    module_ids: checkedRoles
                };
                api.ajax.post("/role/merge", params).then(function (result) {
                    that.$confirm('修改成功，是否现在刷新页面获取权限菜单？', '提示')
                        .then(() => {
                          window.location.replace('');
                        })
                }, function (result) {
                    that.$alert("获取该角色的模块信息失败", '失败!');
                });
            }
        },
        created() {
        },
        mounted() {
            this.getModules();
        },
        activated() {
        }
    }
</script>

<style scoped>

</style>
